<template>
    <div class="icon-selector">
        <el-popover placement="bottom" :width="fontIconWidth" v-model:visible="fontIconVisible" popper-class="icon-selector-popper">
            <template #reference>
                <el-input
                v-model="fontIconSearch"
                :placeholder="fontIconPlaceholder"
                :clearable="clearable"
                :disbaled="disabled"
                :size="size"
                ref="inputWidthRef"
                @clear="onClearFontIcon"
                @focus="onIconFocus"
                >
                    <template #prepend>
                        <SvgIcon :name="fontIconPreFix === '' ? prepend : fontIconPrefix " class="font14" v-if="fontIconPreFix === '' ? prepend?.indexOf('ele-') > -1 :fontIconPrefix?.indexOf('ele-') > -1 " />
                        <i v-else :class="fontIconPrefix === '' ? prepend : fontIconPreFix" class="font14"></i>
                    </template>
                </el-input>
            </template>
            <transition name="el-zoom-in-top">
                <div class="iconselector-warp" v-show="fontIconVisible">
                    <div class="icon-selector-warp-title felx">
                        <div class="flex-auto">{{title}}</div>
                        <div class="icon-selector-warp-title-tab" v-if="type === 'all'">
                            <span :class="{'span-active':fontIconType ==='ali'}" @click="onIconChange('ali')" class="ml10" title="iconfont图标">ali</span>
                            <span :class="{'span-active':fontIconType ==='ele'}" @click="onIconChange('ele')" class="ml10" title="elementPlus">ele</span>
                            <span :class="{'span-active':fontIconType ==='awe'}" @click="onIconChange('awe')" class="ml10" title="fontawesome">awe</span>
                        </div>
                    </div>
                    <div class="icon-selector-warp-row">
                        <el-scrollbar ref="selectorScrollbarRef">
                            <el-row :gutter="10" v-if="fontIconSheetsFilterList.length > 0">
                                <el-col :xs="6" :sm="4" :lg="4" :xl="4" @click="onColClick(v)" v-for="(v,k) in fontIconSheetsFilterList" :key="k">
                                    <div class="icon-selector-warp-item" :class="{'icon-selector-active':fontIconPrefix === v}">
                                        <div class="flex-margin">
                                            <div class="icon-selector-warp-item-value">
                                                <SvgIcon :name="v" />
                                            </div>
                                        </div>
                                    </div>
                                </el-col>
                            </el-row>
                            <el-empty :image-size="100" v-if="fontIconSheetsFilterList.length <= 0" :description="emptyDescription"></el-empty>
                        </el-scrollbar>
                    </div>
                </div>
            </transition>
        </el-popover>
    </div>
</template>
<script lang="ts">
import { defineComponent,reactive,toRefs,ref,onMounted,nextTick,computed,watch } from 'vue';
import initIconfont from '/@/utils/getStyleSheets';
export default defineComponent({
    name:'iconSelector',
    emit:['update:modelValue','get','clear'],
    props:{
        // 输入框前置内容
        prepend:{
            type:String,
            default:()=> 'ele-Pointer',
        },
        // 输入框占位文本
        placeholder:{
            type:String,
            default:()=> '请输入内容搜索图标或者选择图标'
        },
        size:{
            type:String,
            default:()=>'default',
        },
        title:{
            type:String,
            default:()=> '请选择图标'
        },
        type:{
            type:String,
            default:()=>'ele'
        },
        disabled:{
            type:Boolean,
            default:()=> false
        },
        clearable:{
            type:Boolean,
            default:()=> true
        },
        emptyDescription:{
            type:String,
            default:()=>'无相关图标'
        },
        modelValue:String,
    },
    setup(props,{emit}) {
        const inputWidthRef = ref();
        const selectorScrollbarRef = ref();
        const state = reactive({
            fontIconPrefix: '',
			fontIconVisible: false,
			fontIconWidth: 0,
			fontIconSearch: '',
			fontIconTabsIndex: 0,
			fontIconSheetsList: [],
			fontIconPlaceholder: '',
			fontIconType: 'ali',
			fontIconShow: true,
        })
        const onIconFocus = ()=>{
            state.fontIconVisible = true;
            if(!props.modelValue) return false;
            state.fontIconSearch = '';
            state.fontIconPlaceholder = props.modelValue
        }
        const onIconBlur = ()=>{
            setTimeout(()=>{
                const icon = state.fontIconSheetsList.filter((icon:string)=> icon === state.fontIconSearch);
                if(icon.length <=0) state.fontIconSearch = '';
            },300)
        }
        const initModeValueEcho =()=>{
            if(props.modelValue === '') return false;
            (<string | undefined>state.fontIconPlaceholder) = props.modelValue;
            (<string | undefined>state.fontIconPrefix) = props.modelValue;
        }
        const fontIconSheetsFilterList =computed(()=>{
            if(!state.fontIconSearch) return state.fontIconSheetsList;
            let search = state.fontIconSearch.trim().toLowerCase();
            return state.fontIconSheetsList.filter((item:any)=>{
                if(item.toLowerCase().indexOf(search)!== -1) return item;
            })
        })
        const getInputWidth = ()=>{
            nextTick(()=>{
                state.fontIconWidth = inputWidthRef.value.$el.offsetWidth;
            })
        }
        const initResize = ()=>{
            window.addEventListener('resize',()=>{
                getInputWidth()
            })
        }
        const initFontIconData = async(type:string)=>{
            state.fontIconSheetsList = [];
			if (type === 'ali') {
				await initIconfont.ali().then((res: any) => {
					// 阿里字体图标使用 `iconfont xxx`
					state.fontIconSheetsList = res.map((i: string) => `iconfont ${i}`);
				});
			} else if (type === 'ele') {
				await initIconfont.ele().then((res: any) => {
					state.fontIconSheetsList = res;
				});
			} else if (type === 'awe') {
				await initIconfont.awe().then((res: any) => {
					// fontawesome字体图标使用 `fa xxx`
					state.fontIconSheetsList = res.map((i: string) => `fa ${i}`);
				});
			}
			// 初始化 input 的 placeholder
			// 参考（单项数据流）：https://cn.vuejs.org/v2/guide/components-props.html?#%E5%8D%95%E5%90%91%E6%95%B0%E6%8D%AE%E6%B5%81
			state.fontIconPlaceholder = props.placeholder;
			// 初始化双向绑定回显
			initModeValueEcho();
			// 切换时，滚动条置顶。感兴趣可以使用 keep-alive <component :is="xxx"/> 进行缓存
			selectorScrollbarRef.value.wrap$.scrollTop = 0;
        }
        const onIconChange = (type:string)=>{
            state.fontIconType = type;
            initFontIconData(type);
        }
        const onColClick =(v:any)=>{
            state.fontIconPlaceholder = v;
            state.fontIconVisible = false;
            state.fontIconPrefix = v;
            emit('get',state.fontIconPrefix)
            emit('update:modelValue',state.fontIconPrefix)
        }
        const onClearFontIcon =()=>{
            state.fontIconPrefix = '';
			emit('clear', state.fontIconPrefix);
			emit('update:modelValue', state.fontIconPrefix);
        }
        onMounted(()=>{
            if(props.type==='all'){
                if ((<any>props.modelValue)?.indexOf('iconfont') > -1) onIconChange('ali');
				else if ((<any>props.modelValue)?.indexOf('ele-') > -1) onIconChange('ele');
				else if ((<any>props.modelValue)?.indexOf('fa') > -1) onIconChange('awe');
				else onIconChange('ali');
            }else{
                onIconChange(props.type);
            }
            initResize();
            getInputWidth();
        })
        watch(
            ()=>{props.modelValue},
            ()=>{
                 initModeValueEcho()
            }
        )
        return{
            inputWidthRef,
            selectorScrollbarRef,
            fontIconSheetsFilterList,
            onIconChange,
            onColClick,
            onClearFontIcon,
            onIconFocus,
            onIconBlur,
            ...toRefs(state)

        }
        
    },
})
</script>
